import '@/design/windicss/windi-base.css';
import '@/design/windicss/windi-components.css';
import '@/design/windicss/windi-utilities.css';
import '@/design/index.less'
import 'virtual:svg-icons-register'
// @ts-ignore
import Taishan from 'allin-taishan-component'
import FullCalendar from '@allin-components/full-calendar'
import Antd from 'ant-design-vue'
import * as AntdIcon from '@ant-design/icons-vue'
import { createApp } from 'vue'
import { setupStore } from '@/store'
import { setupRouter } from '@/router'
import { setupI18n } from '@/locales'

import { Vue3ProgressPlugin } from '@marcoschulte/vue3-progress'
import '@marcoschulte/vue3-progress/dist/index.css'
import Directives from '@/directives/index'

// Importing on demand in local development will increase the number of browser requests by around 20%.
// This may slow down the browser refresh speed.
// Therefore, only enable on-demand importing in production environments .
import('ant-design-vue/dist/antd.less')
const microAppData = window.microApp?.getData() ?? window.eventCenterForViteApp?.getData()
if (!microAppData) {
    import('allin-taishan-component/lib/theme-default/index.less')
    import('@allin-components/full-calendar/lib/style.css')
}
import App from './App.vue'
// 注册dayjs插件
import dayjs from 'dayjs'
import weekday from 'dayjs/plugin/weekday'
import weekOfYear from 'dayjs/plugin/weekOfYear'
import LocaleData from 'dayjs/plugin/localeData'
dayjs.extend(weekday)
dayjs.extend(weekOfYear)
dayjs.extend(LocaleData)

let app = null
const bootstrap = () => {
    app = createApp(App)
    app.use(Vue3ProgressPlugin)
    app.config.ignoredElements = ['micro-app']

    app.use(Directives)
    app.use(Taishan)
    app.use(FullCalendar)
    app.use(Antd)
    Object.keys(AntdIcon).forEach(item => {
        if (
            item === 'default' ||
            item === 'createFromIconfontCN' ||
            item === 'getTwoToneColor' ||
            item === 'setTwoToneColor'
        ) {
            return
        }
        // @ts-ignore
        app.component(item, AntdIcon[item])
    })

    setupStore(app)
    setupRouter(app)
    setupI18n(app)

    // 如果在micro app中，可能会使用同一个DOM元素挂载Vue应用，这里需要判断是否存在vue应用，如果存在，在执行卸载操作
    const container = document.querySelector('#' + import.meta.env.VITE_APP_ID)
    if (container) {
        if (container.__vue_app__) {
            container.__vue_app__.unmount()
        }
        container.innerHTML = ''
    }
    app.mount('#' + import.meta.env.VITE_APP_ID)
}
function unmount () {
    app.unmount()
    app = null
}
// 微前端环境下，子应用注册mount和unmount方法
if (window.__MICRO_APP_ENVIRONMENT__) {
    window[`micro-app-${window.__MICRO_APP_NAME__}`] = { mount: bootstrap, unmount }
} else {
    // 非微前端环境直接渲染
    bootstrap()
}
